<template>
    <div class="container" style="align-items: stretch">
        <div class="content">
            <div class="hotel-detail">
                <div class="hotel-header" v-if="hotel">
                    <el-image v-if="hotel.photos" :src="hotel.photos[0]?.url"
                        fit="cover" class="hotel-image" />
                    <el-image v-else :src="hotel.photo" fit="cover" class="hotel-image" />
                    <div class="hotel-info">
                        <h1>{{ hotel.name }}</h1>
                        <el-rate v-if="hotel.biz_ext && hotel.biz_ext.rating" :value="hotel.biz_ext.rating" disabled />
                        <p v-else>评分：暂无</p>
                        <p>位置：{{ hotel.address ? hotel.address : '地址迁移' }}</p>
                        <p>距离：{{ hotel.distance ? `${hotel.distance} 米` : '暂无参考' }}</p>
                        <p>类型：{{ hotel.type ? hotel.type : '暂无类型信息' }}</p>
                        <p>价格：¥{{ computedPrice }}</p>
                    </div>
                </div>
                <el-form ref="bookingForm" :model="bookingData" label-width="120px" class="booking-form">
                    <div class="form-row">
                        <el-form-item label="房间类型">
                            <el-radio-group v-model="bookingData.roomType">
                                <el-radio label="大床房">大床房</el-radio>
                                <el-radio label="双床房">双床房</el-radio>
                            </el-radio-group>
                        </el-form-item>
                        <el-form-item label="窗户">
                            <el-radio-group v-model="bookingData.window">
                                <el-radio label="无窗">无窗</el-radio>
                                <el-radio label="有窗">有窗</el-radio>
                            </el-radio-group>
                        </el-form-item>
                        <el-form-item label="早餐">
                            <el-radio-group v-model="bookingData.breakfast">
                                <el-radio label="无">无</el-radio>
                                <el-radio label="有">有</el-radio>
                            </el-radio-group>
                        </el-form-item>
                    </div>
                    <div class="input-group">
                        <label for="checkin">入住日期：</label>
                        <input type="date" v-model="bookingData.checkin" @change="checkDates" required>
                    </div>
                    <div class="input-group">
                        <label for="checkout">离店日期：</label>
                        <input type="date" v-model="bookingData.checkout" @change="checkDates" required>
                    </div>
                    <el-button style="background-color: #7fabbe;" class="input-group" type="primary" @click="bookHotel">预定</el-button>
                </el-form>
            </div>
        </div>
        <!-- <div class="map">
            <AroundMap :location="hotel.location.split(',').map(parseFloat)"
                :marksPosition="[hotel.location.split(',').map(parseFloat)]">
            </AroundMap>
        </div> -->
    </div>
</template>

<script>
import { MessageBox } from "element-ui"
import AroundMap from "./around-map-component.vue";
import api from '@/api';

export default {
    name: 'HotelDetail',
    components: {
        AroundMap
    },
    data() {
        const currentDateStr = this.getCurrentDate();
        // 将当前日期字符串转换为日期对象
        const currentDate = new Date(currentDateStr);
        const tomorrowDate = new Date(currentDate);
        tomorrowDate.setDate(currentDate.getDate() + 1);
        // 将明天的日期转换为字符串
        const tomorrowDateStr = tomorrowDate.toISOString().split('T')[0];
        return {
            currentDateStr: currentDateStr,
            tomorrowDateStr: tomorrowDateStr,
            lowest_price: 100,
            hotel: {
                id: '',
                name: '',
                address: '',
                location: '',
                distance: '',
                biz_ext: { rating: null, },
                type: '',
                photos: [],
            },
            bookingData: {
                hotelId: '',
                username: this.$store.state.user.session.username,
                hotelName: '',
                hotelAddress: '',
                hotelLocation: '',
                roomType: '大床房',
                window: '无窗',
                breakfast: '无',
                checkin: '',
                checkout: '',
                hotelScore: null,
                hotelType: '',
                photo: '',
            },
            dateError: ''
        };
    },
    computed: {
        computedPrice() {
            let price = 200
            if (this.bookingData.roomType === '双床房') price += 20;
            if (this.bookingData.window === '有窗') price += 20;
            if (this.bookingData.breakfast === '有') price += 20;
            this.price = price;
            console.log('this的price', this.price)
            return price;
        }
    },
    created() {
        this.loadHotelData();
    },
    methods: {
        // 获取酒店数据
        loadHotelData() {
            console.log(this.$route.query);
            this.bookingData.checkin = this.$route.query.checkin;
            this.bookingData.checkout = this.$route.query.checkout;
            const storedHotels = this.$route.query.hotel;
            console.log("hoteldetail" + storedHotels);
            if (storedHotels) {
                const hotel = JSON.parse(storedHotels);
                if (hotel) {
                    this.hotel = hotel;
                    this.bookingData.hotelId = hotel.id;
                    this.bookingData.hotelName = hotel.name;
                    this.bookingData.hotelAddress = hotel.address;
                    this.bookingData.hotelType = hotel.type;
                    this.bookingData.hotelLocation = hotel.location.split(',').map(parseFloat);
                    this.bookingData.hotelScore = hotel.biz_ext ? hotel.biz_ext.rating : null;
                    // this.bookingData.price = price;
                    this.bookingData.photo = hotel.photos ? hotel.photos[0].url : hotel.photo;
                } else {
                    this.handleNoHotelData();
                }
            } else {
                this.handleNoHotelData();
            }
        },
        // 获取现在的日期
        getCurrentDate() {
            let today = new Date();
            let month = String(today.getMonth() + 1).padStart(2, '0');
            let day = String(today.getDate()).padStart(2, '0');
            let year = today.getFullYear();
            return `${year}-${month}-${day}`;
        },
        handleNoHotelData() {
            this.$message.warning('暂无本地推荐数据');
            this.hotel = {
                name: '',
                address: '',
                distance: '',
                biz_ext: {
                    rating: null,
                },
                biz_type: '',
                photos: []
            };
        },
        // 检查入住信息
        checkDates() {
            const checkinTimestamp = new Date(this.bookingData.checkin).getTime();
            const checkoutTimestamp = new Date(this.bookingData.checkout).getTime();

            if (checkoutTimestamp < checkinTimestamp) {
                this.bookingData.checkout = this.tomorrowDateStr;
                MessageBox.alert('离店日期不能小于入住日期，请重新选择日期。', '提示', {
                    confirmButtonText: '确定',
                    type: 'warning'
                });
            } else if (checkinTimestamp < new Date().setHours(0, 0, 0, 0)) {
                this.bookingData.checkin = this.currentDateStr;
                MessageBox.alert('入住日期无效，请重新选择日期。', '提示', {
                    confirmButtonText: '确定',
                    type: 'warning'
                });
            }
        },
        // 预定酒店
        bookHotel() {
            if (this.dateError) {
                this.$message.error('请先修正错误');
                return;
            }
            if (!this.bookingData.hotelName) {
                this.$message.error('酒店名字不能为空');
                return;
            }
            console.log('Booking Data:', this.bookingData);
            this.$post(api.hotelbooking, this.bookingData)
                .then((res) => {
                    console.log('Response Data:', res);
                    if (res.success) {
                        const orderId = res.orderId;
                        console.log('price', this.bookingData.price);
                         window.open(`http://localhost:8088/alipay/hotel/pay?amount=${this.price}&orderId=${orderId}`);
                    } else {
                        this.$message.error('预定失败');
                    }
                })
                .catch((err) => {
                    console.error('预定失败:', err);
                    this.$message.error('预定失败');
                });
        },
    }
};
</script>

<style scoped>
.container {
    width: 100%;
    max-width: 1400px;
    display: flex;
    justify-content: space-between;
    margin-top: 20px;

    .content {
        flex: 2;
        background-color: #fff;
        padding: 20px;
        box-shadow: 0 4px 10px rgba(0, 0, 0, 0.1);
        border-radius: 8px;
        margin-right: 20px;

        .hotel-detail {
            width: 800px;
            margin: 10px auto;
            padding: 10px;
        }

        .hotel-header {
            display: flex;
            align-items: center;
        }

        .hotel-image {
            width: 200px;
            height: 150px;
            margin-right: 20px;
        }

        .hotel-info {
            flex: 1;
        }

        .hotel-info h1 {
            border-bottom: 2px solid #81b3c7;
            margin-bottom: 10px;
        }

        .hotel-photos {
            display: flex;
            flex-wrap: wrap;
            margin-top: 20px;
        }

        .photo-item {
            width: 120px;
            height: 120px;
            margin: 5px;
        }

        .booking-form {
            margin-top: 20px;
        }

        .form-row {
            display: flex;
            align-items: center;
            justify-content: space-between;
            padding-right: 100px;

            .el-radio-group {
                width: 162px;
            }
        }

        .form-row .el-form-item {
            flex: 1;
            margin-right: 2px;
        }

        .form-row .el-form-item:last-child {
            margin-right: 0;
        }

        .map {
            flex: 1;
            height: 200px;
            background-color: #e0e0e0;
            border-radius: 8px;
            overflow: hidden;

            img {
                width: 100%;
                height: 100%;
                object-fit: cover;
            }
        }

        .input-group {
            margin-bottom: 15px;
            display: inline-block;
            align-items: center;
            margin-left: 50px;

            .sort-btn {
                margin-left: 10px;
            }

            label {
                margin-right: 10px;
            }

            input,
            select {
                flex: 1;
                padding: 8px;
                border: 1px solid #ccc;
                border-radius: 4px;
                font-size: 14px;
                height: 36px;
            }

            input[type="date"] {
                min-width: 200px;
            }

            input[type="number"] {
                width: 100px;
            }
        }
    }
}
::v-deep .el-radio__input.is-checked .el-radio__inner 
{
    border-color: #7fabbe;
    background: #7fabbe;
}
::v-deep .el-radio__input.is-checked + .el-radio__label {
    color: #7fabbe;
}
</style>